﻿using Cinch;
using CodeSHARPer.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;

namespace CodeSHARPer.ViewModel.Dialogs
{
    public class FolderBrowserViewModel : ViewModelBase
    {
        public FolderBrowserViewModel()
        {
            //commands
            SelectFileCommand = new SimpleCommand<object, object>(OnSelectFile);

            //open the working folder
            ReloadFolders();
        }

        ObservableCollection<FolderRoot> items;
        public ObservableCollection<FolderRoot> Items
        {
            get
            {
                if (items == null)
                    items = new ObservableCollection<FolderRoot>();

                return items;
            }
            set
            {
                items = value;
                NotifyPropertyChanged(ObservableHelper.CreateArgs<FolderBrowserViewModel>(c => c.Items));
                ReloadFolders();
            }
        }

        public void ReloadFolders(string path = "")
        {
            Items.Clear();
            Items.Add(FolderRoot.GetComputer(showFiles: false));
        }

        string folderPath;
        public string FolderPath
        {
            get { return folderPath; }
            set
            {
                folderPath = value;
                NotifyPropertyChanged(ObservableHelper.GetPropertyName<FolderBrowserViewModel>(c => c.FolderPath));
            }
        }

        public Cinch.SimpleCommand<object, object> SelectFileCommand { get; set; }

        internal void OnSelectFile(object args)
        {
            Cinch.EventToCommandArgs eventArgs = args as Cinch.EventToCommandArgs;
            if (eventArgs != null)
            {
                FolderItem item = eventArgs.CommandParameter as FolderItem;
                if (item != null && Directory.Exists(item.FullPath))
                    this.FolderPath = item.FullPath;
            }
        }
    }
}
